import { app, shell, BrowserWindow, ipcMain, Tray, Menu } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { autoUpdater } from 'electron-updater'

let updateWindow = null
function createUpdate(): void {
  // Create the browser window.
  updateWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    // autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      webviewTag: true,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })
  updateWindow.on('ready-to-show', () => {
    updateWindow.show()
  })
  updateWindow.loadFile(join(__dirname, '../../resources/update/index.html'))

  // 版本比较
  autoUpdater.updateConfigPath = join(__dirname, '../../dev-app-update.yml')

  if (is.dev) {
    Object.defineProperty(app, 'isPackages', {
      get() {
        return true
      }
    })
  }

  // 检查是否需要更新版本
  autoUpdater.on('checking-for-update', () => {
    console.log('forUpdate')
    updateWindow.webContents.send('main-to-renderer', {
      name: 'checking-for-update',
      msg: '检查应用版本是否需要更新'
    })
  })
  // 发现新版本，开始下载
  autoUpdater.on('update-available', () => {
    console.log('findNew')
    updateWindow.webContents.send('main-to-renderer', {
      name: 'update-available',
      msg: '检测到新的版本，开始下载'
    })
  })

  //下载的进度
  // autoUpdater.on('download-progress',() => {})

  // 未发现新版本，无需更新
  autoUpdater.on('update-not-available', () => {
    console.log('noFind')
    updateWindow.webContents.send('main-to-renderer', {
      name: 'update-not-available',
      msg: '当前已经是最新版本，无需更新'
    })
  })
  // 下载完成，准备安装
  autoUpdater.on('update-downloaded', () => {
    console.log('downloadEnd')
    updateWindow.webContents.send('main-to-renderer', {
      name: 'update-downloaded',
      msg: '下载完成，准备安装'
    })
  })

  autoUpdater.checkForUpdatesAndNotify()

  // 接收渲染进程传递的数据
  ipcMain.handle('renderer-to-main',( e, data ) => {
    console.log(data)
    if(!data.update){
      //不需要更新
      updateWindow.close()
      createWindow()
    }else{
      //需要更新
      dialog.showMessageBox(updateWindow, {
        title: '版本更新',
        message: '新版本已下载，是否需要重启？',
        buttons: ['确定']
      }).then((res) => {
        console.log(666,res)
        // 该函数会触发应用程序退出当前实例并启动新版本的安装程序
        autoUpdater.quitAndInstall()
      })
    }
  })
}

let mainWindow = null
function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    // autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      webviewTag: true,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  // 设置右键菜单
  const contentMenu = Menu.buildFromTemplate([
    { label: '刷新页面', role: 'reload' },
    { type: 'separator' },
    {
      label: '检查',
      click: () => {
        mainWindow.webContents.openDevTools()
      }
    },
    { type: 'separator' },
    { label: '剪切', role: 'cut' },
    { label: '复制', role: 'copy' },
    { label: '粘贴', role: 'paste' }
  ])
  //监听右键的事件并显示菜单
  mainWindow.webContents.on('context-menu', () => {
    contentMenu.popup({ window: mainWindow })
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  // ipcMain.on('render-to-main', (event, data) => {
  //   console.log('message:', data)
  // })
  // 异步接收消息
  // ipcMain.handle('getTime', async (event, data) => {
  //   return new Date().toLocaleString()
  // })
  // 主进程给渲染进程发送消息
  // setTimeout(() => {
  //   // 注：这里的notify千万别加冒号，因为它是一个名称，在渲染进程里要用的，如果这里加了
  //   // 冒号，渲染进程在接收的时候也要加，它俩必须保持一致
  //   mainWindow.webContents.send('notify', '这是一条主进程发出的消息')
  // }, 5000)

  // createWindow()
  createUpdate()

let wechatWindow = null

  // 绑定微信
  ipcMain.handle('bindWechat', (event, data) => {
    // 创建新窗口
    wechatWindow = new BrowserWindow({
      width: 900,
      height: 670,
      show: false,
      // autoHideMenuBar: true,
      ...(process.platform === 'linux' ? { icon } : {}),
      webPreferences: {
        webviewTag: true,
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false
      }
    })
    wechatWindow.on('ready-to-show', () => {
      wechatWindow.show()
    })
    // 渲染页面
    let { redirectUri, appid, scope, state} = data
    let url = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${decodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
    console.log(url)
    wechatWindow.loadURL(url)
    wechatWindow.webContents.on('will-redirect', (event, newUrl) => {
      const urlParams = new URL(newUrl).searchParams
      const token = urlParams.get('token')
      if (token) {
        mainWindow.webContents.send('main-to-renderer', { data: token})
      }
      wechatWindow.close()
    })
  })

  // 系统托盘
  let tray = new Tray(join(__dirname, '../../resources/logo.ico'))
  const contextMenu = Menu.buildFromTemplate([
    { label: '选项1', type: 'radio' },
    { label: '选项2', type: 'radio' },
    { label: '选项3', type: 'radio', checked: true },
    { label: '选项4', type: 'radio' }
  ])
  tray.setToolTip('这是我的应用！')
  tray.setContextMenu(contextMenu)

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  // 菜单
  const template = [
    {
      label: '文件',
      submenu: [{ label: '退出', role: 'quit', accelerator: 'alt+Q' }]
    },
    {
      label: '编辑',
      submenu: [
        {
          label: '打开控制台',
          accelerator: 'F12',
          click: () => {
            mainWindow.webContents.openDevTools()
          }
        }
      ]
    }
  ]
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
